package com.wkbb.basic.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wkbb.basic.model.Position;
import com.wkbb.basic.vo.TeacherManageVo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.basic.NationalityDto;
import com.wkbb.common.dto.basic.RoleTypeDto;
import com.wkbb.common.dto.basic.RoleTypeJsonDto;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.enums.RelationTypeEnum;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.enums.SexTypeEnum;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.VerifyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author luowenyan
 * @version V1.0
 * @className TipUtil
 * @description excel错误提示辅助类
 * @date 2019/10/19 18:49
 */
public class ExcelErrorTipUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExcelErrorTipUtil.class);

    private final static SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy/MM/dd");
    private final static SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

    //非空提示
    public static String fieldNotNullTip(String fieldName){
        return String.format(ErrorCode.FIELD_NOT_NULL.getMessage(),fieldName,fieldName);
    }

    public static String fieldErrorTip(ErrorCode errorCode,String fieldName){
        return String.format(errorCode.getMessage(),fieldName);
    }

    public static String fieldErrorTip(ErrorCode errorCode,String fieldName,Integer fieldLength){
        return String.format(errorCode.getMessage(),fieldName,fieldLength);
    }

    public static String fieldErrorTip(ErrorCode errorCode,String fieldName,String str){
        return String.format(errorCode.getMessage(),fieldName,str);
    }

    //校验生日，入学日期等日期格式
    public static Boolean checkDateTip(Object dateObj) {
        Boolean isCorrectDate = false;
        try {
            Date newDate = formatObjectDate(dateObj);
            if (null != newDate) {
                isCorrectDate = true;
            }
        } catch (Exception e) {
            isCorrectDate = false;
        }
        return isCorrectDate;
    }

    /**
     * 格式化日期,并返回日期
     * @return
     */
    public static Date formatObjectDate(Object dateObj) throws Exception{
        Date newDate = null;
        if (null != dateObj && dateObj != "") {
            String date = dateObj.toString();
            try{
                if (date.contains("/")) {
                    newDate = simpleDateFormat1.parse(date);
                } else if (date.contains("-")) {
                    newDate = simpleDateFormat2.parse(date);
                }
            }catch (ParseException e){
                throw new Exception("年/月/日格式错误");
            }
        }
        return newDate;
    }

    /**
     * 校验民族
     * @param nationality
     * @param nationalityList
     * @param object
     * @param importFailList
     * @return
     */
    public static Boolean checkNationalityField(String nationality, List<NationalityDto> nationalityList, Object object,Object importFailList) {
        Boolean validFlag = false;
        if(StringUtil.isNotEmpty(nationality)){
            boolean isExist = false;
            for (NationalityDto nationalityDto : nationalityList) {
                if (nationalityDto.getName().trim().equals(nationality)) {
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FIELD_FORMAT_ERROR, ExcelFieldUtil.NATIONALITY,ExcelFieldUtil.NATIONALITY);
                validField(fieldErrorMsg,object,importFailList);
                validFlag = true;
            }
        }
        return validFlag;
    }

    /**
     * 校验岗位
     * @param positionNameObj
     * @param positionList
     * @param teacherManageVo
     * @param importFailList
     * @return
     */
    public static Boolean checkPositionField(Object positionNameObj, List<Position> positionList, TeacherManageVo teacherManageVo, List<TeacherManageVo> importFailList) {
        Boolean validFlag = false;
        if (null != positionNameObj && !"".equals(positionNameObj)) {
            String positionName = positionNameObj.toString();
            boolean isExist = false;
            for (Position position : positionList) {
                if (position.getPositionName().equals(positionName)) {
                    teacherManageVo.setPositionId(position.getId());
                    teacherManageVo.setPositionName(positionName);
                    isExist = true;
                    break;
                }
            }
            if(!isExist){
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FIELD_FORMAT_ERROR,ExcelFieldUtil.POST,ExcelFieldUtil.POST);
                validField(fieldErrorMsg,teacherManageVo,importFailList);
                validFlag = true;
            }
        } else {
            notNullValid(ExcelFieldUtil.POST,teacherManageVo,importFailList);
            validFlag = true;
        }
        return validFlag;
    }

    /**
     * 校验性别
     * @param sexObj
     * @param object
     * @param importFailList
     * @return
     */
    public static Boolean checkSexField(Object sexObj,Object object,Object importFailList){
        Boolean validFlag = false;
        if (null != sexObj && !"".equals(sexObj)) {
            String sex = sexObj.toString();
            if(SexTypeEnum.getValue(sex).intValue()!=SexTypeEnum.MAN.getValue() && SexTypeEnum.getValue(sex).intValue()!=SexTypeEnum.WOMAN.getValue()){
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FIELD_FORMAT_ERROR,ExcelFieldUtil.SEX,ExcelFieldUtil.SEX);
                validField(fieldErrorMsg,object,importFailList);
                validFlag = true;
            }
        } else {
            notNullValid(ExcelFieldUtil.SEX,object,importFailList);
            validFlag = true;
        }
        return validFlag;
    }

    /**
     * 校验日期格式
     * @param dateObject
     * @param object
     * @param importFailList
     * @param dateField
     * @return
     */
    public static Boolean checkDateField(Object dateObject, Object object, Object importFailList, String dateField){
        Boolean validFlag = false;
        if (null != dateObject && !"".equals(dateObject)) {
            Boolean isCorrectDate = checkDateTip(dateObject);
            if (!isCorrectDate) {
                String fieldErrorMsg = fieldErrorTip(ErrorCode.EXCEL_DATE_FORMAT_ERROR,dateField);
                validField(fieldErrorMsg,object,importFailList);
                validFlag = true;
            }
        }
        return validFlag;
    }

    /**
     * 校验学生或家长姓名
     * @param userName
     * @param object
     * @param importFailList
     * @return
     */
    public static Boolean checkUserNameField(String userName,String fieldName,Object object, Object importFailList,Boolean isRequest){
        Boolean validFlag = false;
        if(isRequest){
            if(StringUtils.isEmpty(userName)){
                notNullValid(fieldName,object,importFailList);
                return true;
            }
        }
        if(StringUtil.isNotEmpty(userName)){
            Integer maxLength = 8;
            if(userName.trim().length()>maxLength) {
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FIELD_LENGTH_ERROR,fieldName,maxLength);
                validField(fieldErrorMsg,object,importFailList);
                validFlag = true;
            }else if(VerifyUtil.checkCharacters(userName)){
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FIELD_CHAR_ERROR,fieldName);
                validField(fieldErrorMsg,object,importFailList);
                validFlag = true;
            }
        }
        return validFlag;
    }

    /**
     * 校验手机号
     * @param mobile
     * @param fieldName
     * @param object
     * @param importFailList
     * @param isRequest
     * @return
     */
    public static Boolean checkMobileField(String mobile, String fieldName, Object object, Object importFailList, Boolean isRequest) {
        Boolean validFlag = false;
        if(isRequest){
           /* if (StringUtils.isEmpty(mobile)) {
                notNullValid(fieldName,object,importFailList);
                return true;
            }*/
        }
        if (!StringUtils.isEmpty(mobile)) {
            if (!VerifyUtil.isMobileNum(mobile)) {
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FILED_ERROR,fieldName,fieldName);
                validField(fieldErrorMsg,object,importFailList);
                validFlag = true;
            }
        }
        return validFlag;
    }

    /**
     * //校验家长关系//2、关系符合爸爸、妈妈、爷爷、奶奶、姥姥/外婆、姥爷/外公、亲友”7种类型
     * @param relationTypeName
     * @param studentInfoDto
     * @param importFailList
     * @param isRequest
     */
    public static Boolean checkFamilyRelationField(String relationTypeName,String fieldName,StudentInfoDto studentInfoDto,List<StudentInfoDto> importFailList,Boolean isRequest){
        Boolean validFlag = false;
        if(isRequest){
            /*if(StringUtils.isEmpty(relationTypeName)){
                notNullValid(fieldName,studentInfoDto,importFailList);
                return true;
            }*/
        }
        if (StringUtils.isNotEmpty(relationTypeName)) {
            Integer relationType1 = RelationTypeEnum.getValue(relationTypeName);
            //如果等于其他,表示关系不对
            if(relationType1.intValue()==RelationTypeEnum.OTHER.getValue()){
                String fieldErrorMsg = fieldErrorTip(ErrorCode.FIELD_FORMAT_ERROR,fieldName,fieldName);
                validField(fieldErrorMsg,studentInfoDto,importFailList);
                validFlag = true;
            }
        }
        return validFlag;
    }

    //导入学生时,只有一个不同学校的学生身份才能进行身份合并,否则不进行身份合并
    public static Boolean checkRoleExist(Long newOrgId,Object roleTypeJson){
        List<RoleTypeJsonDto> roleTypeJsons = JSONObject.parseArray(JSON.toJSONString(roleTypeJson), RoleTypeJsonDto.class);
        //logger.info("----checkRoleExist----查询用户角色信息----roleTypeJsons={}", JSONArray.toJSONString(roleTypeJsons));
        Boolean flag = false;
        for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsons) {
            if (roleTypeJsonDto != null && roleTypeJsonDto.getRoleTypes() != null && !roleTypeJsonDto.getRoleTypes().isEmpty()) {
                //同一个学校
                if (roleTypeJsonDto.getOrgId() != newOrgId) {
                    for (RoleTypeDto roleTypeDto : roleTypeJsonDto.getRoleTypes()) {
                        if (RoleTypeEnum.STUDENT.getValue() == roleTypeDto.getRoleType()) {
                            flag = true;
                            break;
                        }
                    }
                }
                if(flag){
                    break;
                }
            }
        }
        return flag;
    }

    //导入老师或家长时
    public static Boolean checkRoleExist(Object roleTypeJson) {
        List<RoleTypeJsonDto> roleTypeJsons = JSONObject.parseArray(JSON.toJSONString(roleTypeJson), RoleTypeJsonDto.class);
        //logger.info("----checkRoleExist----查询用户角色信息----roleTypeJsons={}", JSONArray.toJSONString(roleTypeJsons));
        Boolean flag = false;
        for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsons) {
            if (roleTypeJsonDto != null && roleTypeJsonDto.getRoleTypes() != null && !roleTypeJsonDto.getRoleTypes().isEmpty()) {
                for (RoleTypeDto roleTypeDto : roleTypeJsonDto.getRoleTypes()) {
                    if (RoleTypeEnum.STUDENT.getValue() == roleTypeDto.getRoleType()) {
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * 检查是否是游客身份
     * @param roleTypeJson
     * @return
     */
    public static Boolean checkTouristRole(Object roleTypeJson){
        List<RoleTypeJsonDto> roleTypeJsons = JSONObject.parseArray(JSON.toJSONString(roleTypeJson), RoleTypeJsonDto.class);
        //logger.info("----checkTouristRole----查询用户角色信息----roleTypeJsons={}", JSONArray.toJSONString(roleTypeJsons));
        Boolean isTourist = false;
        for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsons) {
            if (roleTypeJsonDto != null && roleTypeJsonDto.getRoleTypes() != null && !roleTypeJsonDto.getRoleTypes().isEmpty()) {
                for (RoleTypeDto roleTypeDto : roleTypeJsonDto.getRoleTypes()) {
                    if (RoleTypeEnum.TOURIST.getValue() == roleTypeDto.getRoleType()) {
                        isTourist = true;
                    }
                }
            }
        }
        return isTourist;
    }

    /**
     * 非空验证提示
     * @param fieldName
     * @param object
     * @param importList
     */
    public static void notNullValid(String fieldName, Object object,Object importList){
        validField(fieldNotNullTip(fieldName),object,importList);
    }

    public static void validField(ErrorCode errorCode, Object object, Object importList){
        validField(errorCode.getMessage(),object,importList);
    }

    public static void validField(String errorMsg, Object object, Object importList) {
        StudentInfoDto studentInfoDto = null;
        TeacherManageVo teacherManageVo = null;
        if (object instanceof StudentInfoDto) {
            studentInfoDto = (StudentInfoDto) object;
            studentInfoDto.setRemark(errorMsg);
            List<StudentInfoDto> studentFailList = (List<StudentInfoDto>)importList;
            studentFailList.add(studentInfoDto);
        } else if (object instanceof TeacherManageVo) {
            teacherManageVo = (TeacherManageVo) object;
            teacherManageVo.setRemark(errorMsg);
            List<TeacherManageVo> teacherFailList = (List<TeacherManageVo>)importList;
            teacherFailList.add(teacherManageVo);
        }
    }
}
